<template>
	<view class="uni-bg-white h-100">
		<view class="bind-top">
			<image src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/bind-top-bg.png" mode="widthFix" class="bind-top-bg"></image>
			<view class="bind-top-content">
				<uni-nav-bar ref="navBar" fixed statusBar title="成为经纪人" color="#ffffff" :border="false"
					backgroundColor="transparent" @clickLeft="goBack">
					<template v-slot:left>
						<image src="@/applyPages/static/icon-home.svg" mode="widthFix" class="icon-home"></image>
					</template>
				</uni-nav-bar>
				<view class="invite-inner flex flex-col">
					<view class="flex item-center">
						<image :src="codeInner.logo" mode="" class="invite-logo"></image>
						<view class="invite-name">{{codeInner.businessShortName}}</view>
					</view>
					<view class="invite-tip">邀请你成为他的经纪人，</view>
					<text class="strong-tip">轻松赚收益</text>
				</view>
			</view>
		</view>
		<view class="inv-alarm">为确保资金安全及佣金顺利提现，请正确填写以下信息</view>
		<view class="err-msg-box" v-if="submitFlag && msg">
			<view class="err-msg">
				{{msg}}
			</view>
		</view>
		<view class="form-data flex item-center">
			<view class="label-box">姓名：</view>
			<input type="text" placeholder="请输入姓名" class="inp-box w-inp" v-model="formData.username"
				:class="{'unactive':unActiveRule('username')}">
		</view>
		<view class="form-data flex item-center">
			<view class="label-box">手机号：</view>
			<input type="text" placeholder="请输入手机号" class="inp-box w-inp" v-model="formData.mobile"
				:class="{'unactive':unActiveRule('mobile')}">
		</view>
		<view class="form-data flex flex-col">
			<view class="label-box">申请说明：</view>
			<textarea class="w-full fs-14 area-box text-color-regular" placeholder="请输入申请理由(选填)" maxlength="200" v-model="formData.applyReason" />
		</view>
		<view class="k-page"></view>
		<view class="btn-box">
			<view class="release-btn" @click="nextStep">确认提交</view>
		</view>
	</view>
</template>

<script setup>
	import uniDataCheckbox from '@/applyPages/uni_modules/uni-data-checkbox/components/uni-data-checkbox/uni-data-checkbox.vue';
	import {
		ref
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		getByInviteCode,
		agentBindApply,
		bindPreApplyBusiness
	} from '@/api/business.js';
	import {
		useUserStore
	} from '@/stores/modules/user.js'
	import { parseScene, checkPhoneNumber } from '@/utils/index.js'
  import {modelShowToast} from "../../utils";
	const userStore = useUserStore()
	const code = ref()
	const codeInner = ref({})
	const submitFlag = ref(false)
	const msg = ref('')
	const formData = ref({
		"code": "",
		"username": "",
		"applyReason": "",
		"mobile": "",
		"groupId": "",
	})
	const goBack = () => {
		uni.reLaunch({
			url: "/pages/home/home"
		});
	}
	const lingHomePage = (agentLevel) => {
    if (agentLevel === 1) {
      uni.redirectTo({
        url:`/pagesA/merchant/homepage?id=${codeInner.value.id}&incode=${code.value}`
      })
    } else {
      uni.reLaunch({
        url: "/pages/home/home?tab=4"
      });
    }
	}
  // 状态：0-未申请，1-待审核，2-已通过，3-未通过
	const getPreApply = async () => {
		bindPreApplyBusiness({
			settleCode: code.value
		},{linkParamsUrl:`re=bbus&code=${code.value}`}).then(result => {
      if (result) {
        if (result.state === 1) {
          uni.showToast({
            icon:'none',
            title:`申请已提交，待上级经纪人审核`,
            complete() {
              setTimeout(() => {
                uni.reLaunch({
                  url: "/pages/home/home?tab=4"
                });
              },1000)
            }
          })
        } else if (result.state === 2) {
          lingHomePage(result.agentLevel)
        } else if (result.state === 3) {
          formData.value.applyReason = result.applyReason
          formData.value.username = result.username
          formData.value.mobile = result.mobile
          modelShowToast({
            title: '审核未通过',
            content: '原因：' + result.refuseReason + "。请修改后重新提交",
            showCancel:false,
            confirmColor:'#FA4543'
          })
        }
      }
		}).catch(err => {
			uni.showToast({
				icon:'none',
				title:err.message,
				complete() {
					setTimeout(() => {
						if(err.code == 10013){
							lingHomePage(2)
						}else{
							uni.reLaunch({
								url: "/pages/home/home?tab=4"
							});
						}
						
					},1000)
				}
			})
			
		})
		
		
	}
	const getInner = async () => {
		let result = await getByInviteCode({
			inviteCode: code.value
		},{linkParamsUrl:`re=bbus&code=${code.value}`})
		if (result) {
			codeInner.value = result
		}
		getPreApply()
	}
	const unActiveRule = (name) => {
		if (submitFlag.value) {
			if (!formData.value[name] && String(formData.value[name]) != '0') {
				return true
			}
		}
		return false
	}
	const nextStep = async () => {
		let form = formData.value
		submitFlag.value = true
		msg.value = ''
		if (!form.username) {
			msg.value = '请输入姓名'
			return
		}
		if (!form.mobile) {
			msg.value = '请输入手机号'
			return
		}
		if (!checkPhoneNumber(form.mobile)) {
			msg.value = '请输入正确的联系人手机号'
			return
		}
		uni.showLoading({mask:true})
		agentBindApply(form).then(result => {
			uni.hideLoading()
			userStore.getUserInfo()
			lingHomePage(result)
		}).catch(err => {
			uni.hideLoading()
			uni.showToast({
				icon:'none',
				title:err.message
			})
		})
	}
	onLoad((query) => {
		if(query.code){
			code.value = query.code
			formData.value.code = query.code
			formData.value.groupId = query.groupId
		}
		// 扫码打开
		if (query.scene) {
			const scene = parseScene(query.scene)
			if (!query.code && scene.code) {
				code.value = scene.code
				formData.value.code = scene.code
				formData.value.groupId = scene.groupId
			}
		}
		
		if(!userStore.token){
			if(code.value){
				uni.redirectTo({
					url: `/pagesA/login/login?re=bbus&code=${code.value}`
				})
			}
			
		}else{
			if(code.value){
				getInner()
			}
		}
		
		
	})
</script>

<style scoped lang="scss">
	.h-100 {
		height: 100vh;
	}

	.bind-top {
		position: relative;

		// height: 100%;
		.bind-top-bg {
			width: 100%;
			vertical-align: top;
		}

		.bind-top-content {
			position: absolute;
			z-index: 2;
			top: 0;
			left: 0;
		}

		.icon-home {
			width: 32px;
			height: 32px;
		}
	}

	.form-data {
		margin: 14px 10px;
	}

	.label-box {
		font-size: 14px;
		font-weight: 400;
		line-height: 20px;
		color: rgba(51, 51, 51, 1);
		margin: 0px 10px 0 0;
		min-width: 70px;
	}
	
	.area-box{
		margin-top: 8px;
		background: rgba(245, 245, 245, 1);
		border-radius: 12px;
		padding: 12px;
		border: 1px solid rgba(245, 245, 245, 1);
	}

	.inp-box {
		background: rgba(245, 245, 245, 1);
		height: 44px;
		border-radius: 12px;
		padding: 0 10px;
		line-height: 44px;
		border: 1px solid rgba(245, 245, 245, 1);

		&.unactive {
			border-color: #FA4543;
		}
	}

	.invite-inner {
		margin: 98rpx 0 0 56rpx;

		.invite-name {
			font-size: 16px;
			font-weight: 600;
			line-height: 22px;
			color: #ffffff;
			margin-left: 10px;
		}
	}

	.invite-logo {
		width: 48rpx;
		height: 48rpx;
		// border: 1px solid #ffffff;
		border-radius: 12rpx;
	}

	.invite-tip {
		font-family: PingFang SC;
		font-size: 20px;
		font-weight: 600;
		line-height: 30px;
		color: #ffffff;
		margin-top: 8px;
	}
	.strong-tip {
		font-family: YouSheBiaoTiHei, YouSheBiaoTiHei;
		font-size: 32px;
		font-weight: 600;
		line-height: 48px;
		color: #ffffff;
		letter-spacing: 0px;
		text-align: left;
	}

	.inv-alarm {
		font-family: PingFang SC;
		font-size: 12px;
		font-weight: 400;
		line-height: 36px;
		color: rgba(51, 51, 51, 1);
		background: rgba(245, 245, 245, 1);
		padding-left: 10px;
	}

	.err-msg-box {
		height: 36px;

		.err-msg {
			width: 100%;
			box-sizing: border-box;
			background: rgba(250, 69, 67, 0.3);
			font-family: PingFang SC;
			font-size: 12px;
			font-weight: 400;
			line-height: 36px;
			color: rgba(250, 69, 67, 1);
			padding-left: 10px;
		}
	}

	.icon-date {
		width: 16px;
	}

	.w-inp {
		width: calc(100% - 80px);
	}

	.release-btn {
		// width: 343px;
		height: 46px;
		padding: 12px, 20px, 12px, 20px;
		border-radius: 8px;
		// gap: 10px;
		background: #FA4543;
		color: #ffffff;
		margin: 10px 20px;
		text-align: center;
		line-height: 46px;

		&.unactive {
			background: rgba(169, 171, 172, 1);
		}
	}

	.k-page {
		height: 60px;
	}

	.btn-box {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #ffffff;
		z-index: 7;
	}
</style>
